#!/usr/bin/env python
"multiprocessing模块的子类和队列"

import os
import time
import queue
from multiprocessing import Process, Lock, Queue


class CounterProcess(Process):
	"Process的子类"

	label_str = '\t@'

	def __init__(self, start_int, queue, stdout_lock):  # 为运行中的用处保留状态
		self.state_int = start_int
		self.post_queue = queue
		self.stdout_lock = stdout_lock
		Process.__init__(self)

	def run(self):
		for i_int in range(3):
			time.sleep(1)
			self.state_int += 1
			with self.stdout_lock:
				print(self.label_str, self.pid, self.state_int)  # self.pid为进程号
			self.post_queue.put([self.pid, self.state_int])
		with self.stdout_lock:
			print(self.label_str, self.pid, '-')


def main():
	print('start', os.getpid())
	expected_int = 9

	post_queue = Queue()
	stdout_lock = Lock()
	a_counterprocess = CounterProcess(0, post_queue, stdout_lock)
	b_counterprocess = CounterProcess(100, post_queue, stdout_lock)
	c_counterprocess = CounterProcess(10000, post_queue, stdout_lock)
	a_counterprocess.start()
	b_counterprocess.start()
	c_counterprocess.start()

	while expected_int:
		time.sleep(0.5)

		try:
			data_listint = post_queue.get(block=False)
		except queue.Empty:
			with stdout_lock:
				print('no data...')
		else:
			with stdout_lock:
				print('posted:', data_listint)
			expected_int -= 1

	a_counterprocess.join()
	b_counterprocess.join()
	c_counterprocess.join()

	print('finish', os.getpid(), c_counterprocess.exitcode)


if __name__ == '__main__':
	main()
